package org.teach.study.boot.controller;

import javax.servlet.http.HttpSession;

import org.quincy.rock.core.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.teach.study.boot.entity.User;
import org.teach.study.boot.service.UserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import springfox.documentation.annotations.ApiIgnore;

/**
 * <b>PublicControler。</b>
 * <p><b>详细说明：</b></p>
 * <!-- 在此添加详细说明 -->
 * 无。
 * 
 * @version 1.0
 * @author mex2000
 * @since 1.0
 */
@CrossOrigin
@Slf4j
@Api(tags = "公用模块")
@Controller
@RequestMapping("/")
public class PublicControler {
	public static final String PUBLIC_LOGIN_USER_KEY = "loginUser";
	@Autowired
	private UserService userService;

	@ApiOperation(value = "用户登录", notes = "可以自己添加验证码功能")
	@ApiImplicitParams({ @ApiImplicitParam(name = "code", value = "用户代码", required = true),
			@ApiImplicitParam(name = "pwd", value = "密码", required = true) })
	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public @ResponseBody Result<Boolean> login(@RequestParam String code, @RequestParam String pwd,
			@ApiIgnore HttpSession session) {
		log.debug("call login");
		User user = userService.findValidUser(code, pwd);
		if (user != null)
			session.setAttribute(PUBLIC_LOGIN_USER_KEY, user);
		return Result.of(user != null);
	}
	
	@ApiOperation(value = "返回当前用户信息", notes = "未登录则返回null")
	@RequestMapping(value = "/loginUser", method = { RequestMethod.GET })
	public @ResponseBody Result<User> loginUser(@ApiIgnore HttpSession session){
		log.debug("call loginUser");
		User user=(User)session.getAttribute(PUBLIC_LOGIN_USER_KEY);
		return Result.toResult(user);
	}
}
